package tankproject;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class Game extends JPanel {

    private TankController tankController;
    private Vehicle vehicles []=new Vehicle[5];

    public Game() {
        setFocusable(true);
        setDoubleBuffered(true);

        initTank();
        initVehicle();
        initTimerLoop();

        addKeyListener(new GameKeyAdapter());
        addMouseListener(new GameMouseAdapter());
    }

    private void initTank() {
        tankController = new TankController(this);
    }
    private void initVehicle() {
       for (int i=0;i<vehicles.length;i++){
           vehicles[i]=new Vehicle(this,80*i,80*i); 
       }
    }
    private void initTimerLoop() {
        Timer t = new Timer();
        t.scheduleAtFixedRate(new GameTimer(this), 0, 1000 / 40);
    }

    public void update() {
        tankController.update();
        repaint();
    }

    public void paint(Graphics g) {
        super.paint(g);
        tankController.paint(g);
        for (int i=0;i<vehicles.length;i++){
           vehicles[i].paint(g);
       }
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

    /**
     * Get the mouse position or the 0,0 point if it is not avialable.
     */
    public Point getMouseOrZeroPoint() {
        Point mouse = getMousePosition();
        if (mouse == null)
            return new Point(0, 0);
        return mouse;
    }

    private class GameKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            tankController.keyPressed(e);
        }
    }

    private class GameMouseAdapter extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            tankController.mouseClicked(e);
        }
    }

    private class GameTimer extends TimerTask {
        private Game game;
        public GameTimer(Game game) {
            this.game = game;
        }

        public void run() {
            game.update();
        }
    }

}
